import CardTitle from '@/components/CardTitle';
import { Area, Column, measureTextWidth } from '@ant-design/charts';
import ProCard, { StatisticCard } from '@ant-design/pro-card';
import { ProColumns } from '@ant-design/pro-components';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Col, Row, Skeleton } from 'antd';
import RcResizeObserver from 'rc-resize-observer';
import { useEffect, useRef, useState } from 'react';
import style from './index.less';
import { DesktopOutlined, WechatOutlined } from '@ant-design/icons';
import { overview, pageLoginlog } from '@/services/api/api-user-analysis';
interface PreviewFlowProps { }

const PreviewFlow: React.FC<PreviewFlowProps> = ({ }) => {
  const [responsive, setResponsive] = useState(false);

  const userRef = useRef<ActionType>();
  const [previewFlowData, setPreviewFlowDataState] = useState<UserAnalysisData.Overview>();
  const columns: ProColumns<UserData.Loginlog>[] = [
    {
      title: '姓名',
      key: 'accountName',
      hideInSearch: true,
      dataIndex: 'accountName',
      width: '80px',
      render: (_, row) => {
        return <div>
          {row.loginType === '1' ? <WechatOutlined /> : <DesktopOutlined />}
          <span style={{ marginLeft: 5 }}>{row.accountName}</span>
        </div>
      }
    },
    {
      title: '单位',
      key: 'organizationName',
      hideInSearch: true,
      dataIndex: 'organizationName',
      width: '150px',
    },
    // {
    //   title: '操作类型',
    //   key: 'loginEvent',
    //   hideInSearch: true,
    //   dataIndex: 'loginEvent',
    //   valueType: 'select',
    //   width: '80px',
    //   valueEnum: {
    //     1: { text: '登录', status: 'Success' },
    //     2: { text: '登出', status: 'Error' },
    //   },
    // },
    // {
    //   title: '登录方式',
    //   key: 'loginType',
    //   hideInSearch: true,
    //   dataIndex: 'loginType',
    //   valueType: 'select',
    //   width: '80px',
    //   valueEnum: {
    //     1: { text: '微信' },
    //     2: { text: '账号' },
    //     3: { text: '小程序' },
    //   },
    // },
    {
      title: '时间',
      key: 'createdTime',
      hideInSearch: true,
      dataIndex: 'createdTime',
      width: 150,
    },
  ]

  useEffect(() => {
    loadData();
  }, []);

  /**
   * 本月选题计划（数据概览）
   */
  const loadData = async () => {
    try {
      const response = await overview();
      if (response.code === 0) {
        setPreviewFlowDataState(response.data);
      }
    } catch (error) { }
  };
  const areaConfig = {
    height: 275,
    data: previewFlowData?.flowAreas,
    xField: 'date',
    yField: 'count',
    xAxis: {
      range: [0, 1],
    },
    meta: {
      count: {
        alias: '登录次数',
      },
    },
    areaStyle: () => {
      return {
        fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
      };
    },
  };

  const columnConfig = {
    height: 275,
    data: previewFlowData?.flowColumns,
    isStack: true,
    xField: 'date',
    yField: 'count',
    seriesField: 'name',
    columnWidthRatio: 0.3,
    legend: {
      position: 'top', // 将图例放在图的上方
      itemHeight: 20,
    },
    label: {
      // 可手动配置 label 数据标签位置
      position: 'middle',
      // 'top', 'bottom', 'middle'
      // 可配置附加的布局方法
      layout: [
        // 柱形图数据标签位置自动调整
        {
          name: 'interval-adjust-position',
        }, // 数据标签防遮挡
        {
          name: 'interval-hide-overlap',
        }, // 数据标签文颜色自动调整
        {
          name: 'adjust-color',
        },
      ],
    },
  };

  const pieConfig = {
    height: 300,
    // autoFit: true,
    appendPadding: 10,
    data: previewFlowData?.flowPies,
    angleField: 'count',
    colorField: 'name',
    radius: 1,
    innerRadius: 0.64,
    label: {
      type: 'inner',
      offset: '-50%',
      style: {
        textAlign: 'center',
      },
      autoRotate: false,
      // content: '{count}',
    },
    statistic: {
      title: {
        offsetY: -4,
        customHtml: (
          container: { getBoundingClientRect: () => { width: any; height: any } },
          view: any,
          datum: { name: any },
        ) => {
          const { width, height } = container.getBoundingClientRect();
          const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
          const text = datum ? datum.name : '总计';
          return renderStatistic(d, text, {
            fontSize: 28,
          });
        },
      },
      content: {
        offsetY: 4,
        style: {
          fontSize: '32px',
        },
        customHtml: (
          container: { getBoundingClientRect: () => { width: any } },
          view: any,
          datum: { count: any },
          data: any[],
        ) => {
          const { width } = container.getBoundingClientRect();
          const text = datum
            ? `${datum.count} 人次`
            : `${data.reduce((r, d) => r + d.count, 0)}人次`;
          return renderStatistic(width, text, {
            fontSize: 32,
          });
        },
      },
    },
    // 添加 中心统计文本 交互
    interactions: [
      {
        type: 'element-selected',
      },
      {
        type: 'element-active',
      },
      {
        type: 'pie-statistic-active',
      },
    ],
  };

  function renderStatistic(containerWidth: number, text: string, style: { fontSize: number }) {
    const { width: textWidth, height: textHeight } = measureTextWidth(text, style);
    const R = containerWidth / 2; // r^2 = (w / 2)^2 + (h - offsetY)^2

    let scale = 1;

    if (containerWidth < textWidth) {
      scale = Math.min(
        Math.sqrt(
          Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2))),
        ),
        1,
      );
    }

    const textStyleStr = `width:${containerWidth}px;`;
    return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'
      };">${text}</div>`;
  }

  return (
    <RcResizeObserver
      key="resize-observer"
      onResize={(offset) => {
        setResponsive(offset.width < 596);
      }}
    >
      <>
        <ProCard
          title={<CardTitle>用户登录</CardTitle>}
          // extra={moment().format('LLLL')}
          split={responsive ? 'horizontal' : 'vertical'}
          headerBordered={false}
          bordered={false}
        >
          <div style={{ padding: '20px' }}>
            <Skeleton loading={previewFlowData?.flowDay.dayCount === undefined} active avatar>
              <ProCard
                headerBordered={false}
                bordered={false}
                direction={responsive ? 'column' : 'row'}
              >
                <ProCard
                  headerBordered={false}
                  bordered={false}
                  className={style.today}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '95%' }}
                >
                  <h3>{previewFlowData?.flowDay.title}</h3>
                  <h2 style={{ color: '#467BE3' }}>{previewFlowData?.flowDay.dayCount}</h2>
                  <StatisticCard.Statistic
                    title={previewFlowData?.flowDay.daySubtitle}
                    value={previewFlowData?.flowDay.dayTrendCount + ' '}
                    trend={previewFlowData?.flowDay.dayTrend}
                  />
                </ProCard>
                <ProCard
                  bordered={false}
                  className={style.month}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '95%' }}
                >
                  <h3>{previewFlowData?.flowMonth.title}</h3>
                  <h2 style={{ color: '#467BE3' }}>{previewFlowData?.flowMonth.monthCount}</h2>
                  <StatisticCard.Statistic
                    title={previewFlowData?.flowMonth.monthSubtitle}
                    value={previewFlowData?.flowMonth.monthTrendCount + ' '}
                    trend={previewFlowData?.flowMonth.monthTrend}
                  />
                </ProCard>
                <ProCard
                  bordered={false}
                  className={style.threeMonth}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '95%' }}
                >
                  <h3>三日内登录账户数</h3>
                  <h2 style={{ color: '#467BE3' }}>
                    {previewFlowData?.accountLoginHistoryForThreeDays}个
                  </h2>
                </ProCard>
                <ProCard
                  bordered={false}
                  className={style.wxUser}
                  split={responsive ? 'horizontal' : 'vertical'}
                  style={{ padding: '10px 40px', width: '95%' }}
                >
                  <h3>绑定微信账户数</h3>
                  <h2 style={{ color: '#467BE3' }}>{previewFlowData?.bindingWeChat}个</h2>
                </ProCard>
              </ProCard>
            </Skeleton>
            <Skeleton loading={previewFlowData?.flowAreas === undefined} active avatar>
              <Row>
                <Col xl={12} lg={24} md={24} sm={24} xs={24} style={{ marginTop: 40 }}>
                  {previewFlowData && (
                    <StatisticCard title="七日内登录次数走势" chart={<Area {...areaConfig} />} />
                  )}
                </Col>
                <Col xl={12} lg={24} md={24} sm={24} xs={24} style={{ marginTop: 40 }}>
                  {/* {previewFlowData && <Pie {...pieConfig} />} */}
                  {previewFlowData && (
                    <StatisticCard
                      title="七日内登录单位次数占比"
                      chart={<Column {...columnConfig} />}
                      style={{ marginTop: previewFlowData?.flowColumns ? '0' : '-13px' }}
                    />
                  )}
                </Col>
              </Row>
            </Skeleton>
            <ProTable<UserData.Loginlog>
              columns={columns}
              request={async (params = {}) => {
                const response = await pageLoginlog({
                  ...params,
                });

                return Promise.resolve({
                  data: response.data.data,
                  total: response.data.total,
                  success: response.code === 0,
                });
              }}
              rowKey="id"
              dateFormatter="string"
              bordered
              search={{
                filterType: 'light',
              }}

              cardProps={false}
              onHeaderRow={(columns, index) => {
                return {
                  onClick: () => { }, // 点击表头行
                };
              }}
              pagination={{
                showQuickJumper: true,
                showSizeChanger: true,
                defaultPageSize: 10,
              }}

            />
          </div>
        </ProCard>
        <br />
      </>
    </RcResizeObserver>
  );
};

export default PreviewFlow;
